import requests
import json
import cx_Oracle
import time
import random
import string

USER_NAME = '17799308923'
LOGIN_PASSWORD = 'Ztwzjt123456'
APPLICATION_ID = '167010000'
#数据库 标识字段 USCICODE 三证合一号
PRIVATE_USCICODE = '91650400560549616W' # 天山水泥 有7个公司 暂时用吐鲁番天山的
APPID = 'tlfts'  # 吐鲁番天山
PURCHASE_ORDER = '0309' # 采购订单
SALES_ORDER = '0601' # 销售订单
CANCEL_PURCHASE_ORDER = '0317' # 订单终止  采购订单终止
PICK_ORDER = '0401' # 提货单
CANCEL_PICK_ORDER = '0420' # 提单作废
CREATOR = '91510100201961238F'  # 中铁物资
OWNER = '91650400560549616W'  # 吐鲁番天山

# 测试
ORACLE_IP = '1.94.141.230'
PORT = '1521'
SERVICE_NAME = 'orcl'
USER = 'c##dvc'
PASSWORD = 'wafa@123456'
ORACLE_PATH = r"D:\instantclient_12_1"

DVC_ADDRESS = "https://dvc.pangugyl.cn/"

#生产
# ORACLE_IP = '172.16.32.77'
# PORT = '1521'
# SERVICE_NAME = 'xtpdb'
# USER = 'dvc_pro'
# PASSWORD = 'S6(HUF73pa.Ike97'
#
# ORACLE_PATH = r"C:\instantclient_12_1"

# DVC_ADDRESS = "https://dvc.pgyl.cn/"
# DVC_ADDRESS = "http://172.16.32.8:8080/"

def generate_random_id():
    # 获取当前时间戳（精确到毫秒）
    timestamp = int(time.time() * 1000)
    # 生成4个随机大写字母
    random_letters = ''.join(random.choices(string.ascii_uppercase, k=4))
    return f"{timestamp}{random_letters}"

def login():
    '''
    用户名、密码登录
    :return:
    '''
    url = 'http://220.171.97.55:6691' + '/api/SysUser/LoginForTraderByPassWord'
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Linux; Android 12; HBN-AL00 Build/HUAWEIHBN-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/114.0.5735.196 Mobile Safari/537.36 uni-app Html5Plus/1.0 (Immersed/41.185184)'
    }
    payload = {
        'FMobilephone': USER_NAME,
        'FPassword': LOGIN_PASSWORD,
    }
    res = requests.post(url, json=payload, headers=headers)
    res.raise_for_status()
    print(f"\t(调试)账号登陆：{res.json()}\t")
    # 解析数据 存储用户信息
    data = res.json()
    if data.get('IsSuccess'):
        print('获取账号信息成功')
        userInfo = data.get('Data',[])
        return True,'登陆成功',userInfo
    else:
        msg = data.get('Message')
        print(f"\t(调试)登陆失败：{msg}\t")
        return False,msg,[]

def save_user_info(userInfo):
    '''
    存储用户信息
    :return:
    '''
    print(f"\t(调试)待存储的用户信息：{userInfo}\t")
    userInfo_str = json.dumps(userInfo)
    try:
        # 确保 Oracle Instant Client 已初始化
        if not hasattr(cx_Oracle, '_client_initialized') or not cx_Oracle._client_initialized:
            cx_Oracle.init_oracle_client(lib_dir=ORACLE_PATH)
            cx_Oracle._client_initialized = True
        # 创建 DSN 连接字符串
        dsn = cx_Oracle.makedsn(ORACLE_IP, PORT, service_name=SERVICE_NAME)
        # 建立连接
        connection = cx_Oracle.connect(user=USER, password=PASSWORD, dsn=dsn)

        # 创建游标
        cursor = connection.cursor()

        cursor.execute('SELECT COUNT(*) FROM SUPPLIER_LOCAL WHERE USCICODE = :1',(PRIVATE_USCICODE,))
        if cursor.fetchone()[0] > 0:
            cursor.execute('UPDATE SUPPLIER_LOCAL SET ID = :1, VALUE = :2 WHERE USCICODE = :3',(generate_random_id(),userInfo_str,PRIVATE_USCICODE))
            print(f"\t(调试)用户信息更新完成！\t")
        else:
            cursor.execute('INSERT INTO SUPPLIER_LOCAL (ID,VALUE,USCICODE) VALUES (:1, :2, :3)',(generate_random_id(),userInfo_str,PRIVATE_USCICODE))
            print(f"\t(调试)用户信息插入完成！\t")
        connection.commit()
    finally:
        # 关闭游标和连接
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

def get_user_info():
    '''
    从数据库中取存储的用户信息
    :return:
    '''
    try:
        # 确保 Oracle Instant Client 已初始化
        if not hasattr(cx_Oracle, '_client_initialized') or not cx_Oracle._client_initialized:
            cx_Oracle.init_oracle_client(lib_dir=ORACLE_PATH)
            cx_Oracle._client_initialized = True
        # 创建 DSN 连接字符串
        dsn = cx_Oracle.makedsn(ORACLE_IP, PORT, service_name=SERVICE_NAME)
        # 建立连接
        connection = cx_Oracle.connect(user=USER, password=PASSWORD, dsn=dsn)

        # 创建游标
        cursor = connection.cursor()

        cursor.execute("SELECT VALUE FROM SUPPLIER_LOCAL WHERE USCICODE = :1",(PRIVATE_USCICODE,))
        result = cursor.fetchone()
        if result is not None:
            value = result[0]
            userInfo = json.loads(value)
            return True,'获取当前用户信息成功！',userInfo
        else:
            print('没有查到对应的用户信息')
            return False,'没有查到对应的用户信息！',{}

    finally:
        # 关闭游标和连接
        if 'cursor' in locals():
            cursor.close()
        if 'connection' in locals():
            connection.close()

def main():
    login_result = login()
    if login_result[0]:
        print('登陆成功!')
        if not login_result[2]:
            print(f"\t(调试)用户信息为空\t")
            return False,'登陆成功但是用户信息为空'
        else:
            save_user_info(login_result[2][0])
            return True,'登陆成功'
    else:
        print(f"\t(错误)登陆失败：{login_result[1]}\t)")
        return False,f'登陆失败：{login_result[1]}'

if __name__ == '__main__':
    main()